import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import DTO.userinfomation;
@WebServlet("/upload_servlet")
@MultipartConfig(location = "C:\\Users\\zhu\\IdeaProjects\\experiment_15\\src\\main\\webapp\\photo")// location改为本地的绝对路径
public class upload_servlet extends HttpServlet{
    public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
        Part part = req.getPart("userhead");
        ArrayList<userinfomation> user_array = new ArrayList<userinfomation> ();
        Map<String,String> user =(Map<String ,String>)req.getSession().getAttribute("USER");
        String username = user.get("username");
        String filename =  username.concat(".jpg");
        part.write(filename);
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("login.txt")));
        String string = null;
        Jsonb jsonb = JsonbBuilder.create();
        userinfomation user_old = new userinfomation();
        userinfomation user_new = new userinfomation();
        while((string = reader.readLine()) != null)//把更新好的数据放入str_array中
        {
             user_old = jsonb.fromJson(string,userinfomation.class);
             if(user_old.getUsername().equals(username)){//找到这个人
                 user_new = new userinfomation(user_old.getUsername(),user_old.getPasswd(),user_old.getPhone(),filename);
                 user_array.add(user_new);
             }
            else user_array.add(user_old);
        }
        reader.close();
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("login.txt",false)));
        for(int i = 0;i< user_array.size(); i++)//将更新后的信息与没有更新的写入Login.txt
        {
            String string_new = jsonb.toJson(user_array.get(i));
            out.write(string_new+"\n");
        }
        out.close();
        //将本session对应的用户里面的img信息更改
        user.put("img",filename);
        HttpSession session = req.getSession(true);
        Map<String,String >map = new HashMap<>();
        map.put("username",user.get("username"));
        map.put("phone",user.get("phone"));
        map.put("password",user.get("password"));
        map.put("img",user.get("img"));
        session.setAttribute("USER",map);
        resp.sendRedirect("user.jsp");
    }
}
